package my.myspring.tool;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import my.tool.ConfigUtil;
import my.tool.ConfigProp;


public class SpringBeanProxy {

    private static ApplicationContext applicationContext;

    static {
        try {
            String classpath = ConfigUtil.getClassPath();
            String springFiles = ConfigProp.getProperties("my.spring.files");
            System.out.println("springFiles=" + springFiles);
            if (!(springFiles == null || springFiles.trim().equals(""))) {
                String[] files = springFiles.trim().split(",");
                ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext(files);
                SpringBeanProxy.setApplicationContext(springContext);
                System.out.println("****************** init spring ... ok ******************");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("****************** init Spring error!!!");
        }
    }

    /**
     * 实现ApplicationContextAware接口的回调方法，设置上下文环境
     *
     * @param applicationContext
     * @throws BeansException
     */
    public synchronized static void setApplicationContext(ApplicationContext arg0) {
        applicationContext = arg0;
    }

    /**
     * @return applicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取对象
     *
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws BeansException
     */
    public static Object getBean(String beanName) throws BeansException {
        return applicationContext.getBean(beanName);
	}

     public static <T> T getBean(String beanName,Class<T> t) throws BeansException {
        return (T)applicationContext.getBean(beanName);
	}
}
